<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UploadFile
 *
 * @author Administrator
 */
class UploadFile extends Filecontrol{
     static private $ins=NULL;
     private $image_config;
     public function __construct() {
          global $_G;
          $this->image_config=$_G["upload_image"];
     }
     //上传文件，参数$_FILES
     public function upload_image($file){
         $msg=array();
         if(isset($file["error"])&&$file["error"] > 0){
             $msg["status"]=0;
             $msg["msg"]="上传出错,错误代码:{$file["error"]}";
             return $msg;
         }
         if(isset($file["size"])){
             $relsize=$file["size"]/1024;
             if($relsize>$this->image_config["image_size"]){
                 
                 $msg["status"]=0;
                 $msg["msg"]="上传文件大小超出！系统限制：{$this->image_config["image_size"]}Kb,实际大小:{$relsize}Kb！";
                 return $msg;
             }
         }
         if(isset($file["type"])&&isset($this->image_config["allow"])){
             $allow=$this->image_config["allow"];
             $type=$file["type"];
             $info = pathinfo($file["name"]);
             $ext=$info["extension"];
             $msg["status"]=0;
             foreach ($allow as $val){
                 if($ext==$val){
                     $msg["status"]=1;
                     break;
                 }
                
             }
             if($msg["status"]==0){
                  $msg["msg"]="上传文件不合法,上传文件格式不在允许范围内！";
                 return $msg;
             }
         }
         
         $imagepath=  $this->image_config["image_path"];
         if(substr($imagepath, -1)=="/"){
             $imagepath.=date("Y-m-d")."/";
         }else{
              $imagepath.="/".date("Y-m-d")."/";
         }
         $rootimage=ROOT.$imagepath;
         $this->mkdirs($rootimage);
         move_uploaded_file($file["tmp_name"], $rootimage.mb_convert_encoding($file["name"],"gbk", "utf-8"));
         $msg["status"]=1;
         $msg["path"]=$imagepath.$file["name"];
         $msg["msg"]="上传文件成功!";
         return $msg;
         
      
     }
     
     
     public  function makethumb($srcFile,$dstFile,$dstW,$dstH,$rate=100,$markwords=null,$markimage=null) 
    {
        global $cfg;
        $srcFile=iconv('UTF-8','gbk',$srcFile);
        $dstFile=iconv('UTF-8','gbk',$dstFile);
        $data = getimagesize($srcFile); 
        switch($data[2]) 
        { 
        case 1: 
            $im=@ImageCreateFromGIF($srcFile); 
            break; 
        case 2: 
            $im=@ImageCreateFromJPEG($srcFile); 
            break; 
        case 3: 
            $im=@ImageCreateFromPNG($srcFile); 
            break; 
        } 
        if(!$im) return false; 
        $srcW=ImageSX($im); 
        $srcH=ImageSY($im); 
        $dstX=0; 
        $dstY=0; 
        //图像比例——宽高计算
        $resize_ratio=$dstW/$dstH;
        $ratio=$srcW/$srcH;
        if($ratio>=$resize_ratio)
        {
            $dstH=$dstW/$ratio;
        }
        else
        {
            $dstW=$dstH*$ratio;
        }
        //
        if ($srcW*$dstH>$srcH*$dstW) 
        { 
          $fdstH = round($srcH*$dstW/$srcW); 
          $dstY = floor(($dstH-$fdstH)/2); 
          $fdstW = $dstW; 
        } 
        else 
        { 
          $fdstW = round($srcW*$dstH/$srcH); 
          $dstX = floor(($dstW-$fdstW)/2); 
          $fdstH = $dstH; 
        } 
        $ni=ImageCreateTrueColor($dstW,$dstH); 
        $dstX=($dstX<0)?0:$dstX; 
        $dstY=($dstX<0)?0:$dstY; 
        $dstX=($dstX>($dstW/2))?floor($dstW/2):$dstX; 
        $dstY=($dstY>($dstH/2))?floor($dstH/s):$dstY; 
        $white = ImageColorAllocate($ni,255,255,255); 
        $black = ImageColorAllocate($ni,0,0,0); 
        imagefilledrectangle($ni,0,0,$dstW,$dstH,$white);// 填充背景色 
        imagecopyresampled($ni,$im,$dstX,$dstY,0,0,$fdstW,$fdstH,$srcW,$srcH); 

        ImageJpeg($ni,$dstFile,$rate);
        if(intval($dstW)>=intval($cfg['sites'][0]['markwaters_width'])||intval($dstH)>=intval($cfg['sites'][0]['markwaters_height'])){
         if($cfg['sites'][0]['markwaters_status']){
        $markwords=$markwords?$markwords:''.$cfg['sites'][0]['watermark_fontstring'];
        $markimage=$markimage?$markimage:UPLOAD_DOMAIN . UPLOAD_DIR .$cfg['sites'][0]['watermark_image'];
        $fontsize=$fontsize?$fontsize:$cfg['sites'][0]['watermark_fontsize'];
        $xcolor=$xcolor?$xcolor:$cfg['sites'][0]['watermark_fontcolor'];
        $xangle=$xangle?$xangle:$cfg['sites'][0]['watermark_angle'];
        $xfont=$xfont?$xfont:  realpath(  UPLOAD_DIR .'font/'.$cfg['sites'][0]['watermark_font']);
        $xfont=$xfont?$xfont:'simhei.ttf';
        $xangle=  empty($xangle)?0:$xangle;
        $xcolor=  empty($xcolor)?'#000000':$xcolor;
        $fontsize=  empty($fontsize)?18:$fontsize;
        }
        
            $niimage_data = GetImageSize($dstFile);
            switch($niimage_data[2]) 
            { 
                case 1: 
                    $niimage=@ImageCreateFromGIF($dstFile); 
                    break; 
                case 2: 
                    $niimage=@ImageCreateFromJPEG($dstFile); 
                    break; 
                case 3: 
                    $niimage=@ImageCreateFromPNG($dstFile); 
                    break; 
            } 
        if($markwords!=null) 
        {
            $hrgb=self::hColor2RGB($xcolor);
            $xcolort=ImageColorAllocate($niimage, $hrgb["r"] ,$hrgb["g"], $hrgb["b"]);
            $wh=self::getwatermarkpos($niimage_data,array($cfg['sites'][0]['watermark_fontwidth'],$cfg['sites'][0]['watermark_fontheight']),"text");
            $markwords=iconv("gb2312","UTF-8",$markwords);
            //转换文字编码 
           $res= ImageTTFText($niimage,$fontsize,$xangle,$wh[0],$wh[1],$xcolort,$xfont,$markwords); //写入文字水印 
            //参数依次为，文字大小|偏转度|横坐标|纵坐标|文字颜色|文字类型|文字内容 
            switch($niimage_data[2]) 
            { 
                case 1: 
               imagegif($niimage,$dstFile);
                    break; 
                case 2: 
               imagejpeg($niimage,$dstFile);
                    break; 
                case 3: 
               imagepng($niimage,$dstFile);
                    break; 
            }
            imagedestroy($wimage);
        }
        if($markimage!=null){ 
            $wimage_data = GetImageSize($markimage); 
            switch($wimage_data[2]) 
            { 
                case 1: 
                    $wimage=@ImageCreateFromGIF($markimage); 
                    break; 
                case 2: 
                    $wimage=@ImageCreateFromJPEG($markimage); 
                    break; 
                case 3: 
                    $wimage=@ImageCreateFromPNG($markimage); 
                    break; 
            } 
            $watermarkpos=self::getwatermarkpos($niimage_data,$wimage_data);
            $res=imagecopy($niimage,$wimage,$watermarkpos[0],$watermarkpos[1],0,0,$wimage_data[0],$wimage_data[1]); //写入图片水印,水印图片大小默认为88*31 
            
            switch($niimage_data[2]) 
            { 
                case 1: 
               imagegif($niimage,$dstFile);
                    break; 
                case 2: 
               imagejpeg($niimage,$dstFile);
                    break; 
                case 3: 
               imagepng($niimage,$dstFile);
                    break; 
            }  
            imagedestroy($wimage);
        } 
            
        }
        imagedestroy($ni);
    }
     public function getImageUrl($file,$style)
    {  
         $img=  $this->getImage($file, $style);
         if(isset($img["imageurl"]))
         return $img["imageurl"];
         else
         return WEBROOT . $this->image_config["image_path"] . 'thumb/' . $style . "/system/nopic.png";;
    }
    public function getImage($file,$style)
    {          
        if(trim($file)=="")
        {
              return WEBROOT .  "system/nopic.png"; 
        }
        $thumb_config = $this->image_config["image_thumb"];
        
        $imagestyle   = in_array($style, $thumb_config) ? $style : ''; 
        $show_url     = '';
        if($imagestyle)
        {
          $file_info   = $this->file_format(trim($file), $imagestyle);
         
          $show_url    = str_replace('#','%23',($file_info['imageurl'])); 
          $style_split = explode('x', $imagestyle) ;
          $width       = $style_split[0]; 
          $height      = $style_split[1];
          
          if (!is_file( iconv('UTF-8','gbk',$file_info['source'])) )
          { //没有源图片
            $format = $width . 'x' . $height;
            $system_source = ROOT.$this->image_config["image_path"] .  "system/nopic.png";
            $imageurl      =  WEBROOT . $this->image_config["image_path"] . 'thumb/' . $format . "/system/nopic.png";
            $target        =   ROOT . $this->image_config["image_path"] . 'thumb/' . $format . "/system/nopic.png";
            
            if (!is_file( $target ) ){                                     
                $path_parts = pathinfo( $target );
                $todir = $path_parts["dirname"] ;
                if( !is_dir($todir) )
                {
                    $this->mkdirs($todir);
                }
               
                $this->makethumb($system_source, $target,$width, $height);
                
            }
            $file_info['target']=$target;
            $file_info['imageurl']=$imageurl;
            $file_info['source']=$system_source;
            
          }
          if (!is_file(iconv('UTF-8','gbk', $file_info['target']) ) )
          {
             
              $path_parts = pathinfo($file_info['target'] );
              $todir = $path_parts["dirname"] ;
            
              if( !is_dir($todir) )
              {
                  $this->mkdirs($todir);
              }
              $this->makethumb($file_info['source'],$file_info['target'],$width, $height);               
          }
        }
        else
        {
          return array(
              "source"=>ROOT .$this->image_config["image_path"].  "system/nopic.png",
              "imageurl"=>WEBROOT . $this->image_config["image_path"] ."system/nopic.png",
              "target"=>ROOT .$this->image_config["image_path"]."system/nopic.png"
          );
        }
        return $file_info;
    }

    public function getImageResize($path,$maxwidth,$maxheight)
    {
        $resize_ratio = $maxwidth / $maxheight ;
        $filearray = getimagesize (  $path );
        $ratio = $filearray[0] / $filearray[1] ;
        if( $ratio >= $resize_ratio)
        {
            return array( $maxwidth , ( $filearray[1] * $maxwidth ) / $filearray[0] ) ;
        }
        else
        {
            return array( ( $filearray[0] * $maxheight ) / $filearray[1] , $maxheight ) ;
        }
    }

    public function deleteImage($file,$arr,$folder="../uploadImage/",$urlstyle=0)
    {
        if($file=="")
            return ;
        if($urlstyle!=1)
        {
            $pic2 = $folder . $file ;
            if ( file_exists( $pic2 ) )
            {
                unlink( $pic2 ) ;
            }
            for($index=1;$index<count($arr);$index++)
            {
                $pic = "../smallImage/" . $arr[$index] . "/" . $file ;
                if ( file_exists( $pic ) )
                {
                    unlink( $pic ) ;
                }
            }
            return true;
        }
        else
        {
            //debug(DELETECDN);
            if( DELETECDN == 1 )
            {
                $http = CGIBIN . "serviceFordeletepimage.php?" . "file=" . urlencode($file) . "&arr=" . urlencode( join('|',$arr) ) . "&folder=" . urlencode($folder) . "&" . REMOTECOMMAND ;
                $text =  file_get_contents( $http ) ;
            }
            //debug($http);
            //debug($text . $http );
        }
    }
   
    public function file_format($file, $format)
    {
       
      if(substr($file, 0, 6) != 'images')
      {
        $source   = ROOT.$this->image_config["image_path"]. $file ;
        $imageurl = WEBROOT.$this->image_config["image_path"] . 'thumb/' . $format . "/" . $file ;
        $target   =   ROOT . $this->image_config["image_path"] . 'thumb/' . $format . "/" . $file ;
      }
      return array('source' => $source, 'imageurl' => $imageurl, 'target' => $target);
    }
   
     /**
     * 颜色字段转换
     */
    public  function hColor2RGB($hexColor){
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3)
        {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else
        {
            $color = str_replace('#', '', $hexColor);
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }
    
     /**
     * 水印位置
     */
    private function getwatermarkpos($x,$y,$type=false){
        global $cfg;
        $res=array(0,0);
        if($type){
            $watemarkpos=$cfg['sites'][0]['watermark_fontpos'];
        }else{
            $watemarkpos=$cfg['sites'][0]['watermarkpos'];
        }
        switch (intval($watemarkpos)) {
            case 0://随机 
            $res[0] = rand(0,($x[0] - $y[0])); 
            $res[1] = rand(0,($x[1] - $y[1])); 
            break; 
            case 1://1为顶端居左 
            $res[0] = 0; 
            $res[1] = 0;
                break;
            case 2://2为顶端居中 
            $res[0] = ($x[0] - $y[0]) / 2;
            $res[1] = 0;
                break;
        case 3://3为顶端居右 
            $res[0]= $x[0] - $y[0]; 
            $res[1] = 0; 
            break; 
        case 4://4为中部居左 
            $res[0]= 0; 
            $res[1] = ($x[1] - $y[1]) / 2; 
            break; 
        case 5://5为中部居中 
            $res[0]= ($x[0] - $y[0]) / 2; 
            $res[1] = ($x[1] - $y[1]) / 2; 
            break; 
        case 6://6为中部居右 
            $res[0]= $x[0] - $y[0]; 
            $res[1] = ($x[1] - $y[1]) / 2; 
            break; 
        case 7://7为底端居左 
            $res[0]= 0; 
            $res[1] = $x[1] - $y[1]; 
            break; 
        case 8://8为底端居中 
            $res[0]= ($x[0] - $y[0]) / 2; 
            $res[1] = $x[1] - $y[1]; 
            break; 
        case 9://9为底端居右 
            $res[0]= $x[0] - $y[0]; 
            $res[1] = $x[1] - $y[1]; 
            break; 
            default:
            $res[0] = 0; 
            $res[1] = 0;
                break;
        }
        return $res;
    }

     //获得类的实例化
    static public function getInstance()
    {
        if(!(self::$ins instanceof self))
        {
            self::$ins=new self();
        }
        return self::$ins;
    }
}
